package com.sz.admin.system.service.impl;

import java.util.ArrayList;
import com.mybatisflex.core.logicdelete.LogicDeleteManager;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.sz.admin.system.mapper.SysDeptLeaderMapper;
import com.sz.admin.system.mapper.SysDeptMapper;
import com.sz.admin.system.mapper.SysUserDeptMapper;
import com.sz.admin.system.mapper.SysUserMapper;
import com.sz.admin.system.pojo.dto.common.SelectorQueryDTO;
import com.sz.admin.system.pojo.dto.sysdept.SysDeptCreateDTO;
import com.sz.admin.system.pojo.dto.sysdept.SysDeptListDTO;
import com.sz.admin.system.pojo.dto.sysdept.SysDeptUpdateDTO;
import com.sz.admin.system.pojo.po.SysDept;
import com.sz.admin.system.pojo.po.SysDeptLeader;
import com.sz.admin.system.pojo.po.SysUser;
import com.sz.admin.system.pojo.po.SysUserDept;
import com.sz.admin.system.pojo.vo.common.DepartmentVO;
import com.sz.admin.system.pojo.vo.sysdept.DeptTreeVO;
import com.sz.admin.system.pojo.vo.sysdept.SysDeptLeaderVO;
import com.sz.admin.system.pojo.vo.sysdept.SysDeptVO;
import com.sz.admin.system.pojo.vo.sysdept.TotalDeptVO;
import com.sz.admin.system.service.SysDeptClosureService;
import com.sz.admin.system.service.SysDeptLeaderService;
import com.sz.admin.system.service.SysDeptService;
import com.sz.admin.system.service.SysUserDeptService;
import com.sz.admin.system.service.SysUserService;
import com.sz.core.common.entity.LoginUser;
import com.sz.core.common.entity.PageResult;
import com.sz.core.common.entity.SelectIdsDTO;
import com.sz.core.common.enums.CommonResponseEnum;
import com.sz.core.common.event.EventPublisher;
import com.sz.core.util.BeanCopyUtils;
import com.sz.core.util.PageUtils;
import com.sz.core.util.TreeUtils;
import com.sz.platform.event.PermissionChangeEvent;
import com.sz.platform.event.PermissionMeta;
import com.sz.security.core.util.LoginUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.Collections;

import static com.mybatisflex.core.query.QueryMethods.*;
import static com.sz.admin.system.pojo.po.table.SysDeptLeaderTableDef.SYS_DEPT_LEADER;
import static com.sz.admin.system.pojo.po.table.SysDeptTableDef.SYS_DEPT;
import static com.sz.admin.system.pojo.po.table.SysUserDeptTableDef.SYS_USER_DEPT;
import static com.sz.admin.system.pojo.po.table.SysUserRoleTableDef.SYS_USER_ROLE;
import static com.sz.admin.system.pojo.po.table.SysUserTableDef.SYS_USER;
import static com.sz.admin.vehicleschedule.pojo.po.table.VehicleScheduleTableDef.VEHICLE_SCHEDULE;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author sz
 * @since 2024-03-20
 */
@Service
@RequiredArgsConstructor
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    private final SysUserMapper userMapper;

    private final SysDeptLeaderMapper leaderMapper;

    private final SysUserDeptMapper sysUserDeptMapper;

    private final SysDeptLeaderService deptLeaderService;

    private final SysDeptClosureService deptClosureService;

    private final SysUserDeptService  userDeptService;
    
    private final EventPublisher eventPublisher;
    
    private final SysUserService sysUserService;

    @Transactional
    @Override
    public void create(SysDeptCreateDTO dto) {
        SysDept sysDept = BeanCopyUtils.copy(dto, SysDept.class);
        if (dto.getPid() == 0) {
            sysDept.setDeep(1);
        } else {
            QueryWrapper wrapper = QueryWrapper.create().eq(SysDept::getId, dto.getPid());
            CommonResponseEnum.INVALID_ID.assertTrue(count(wrapper) <= 0);
            SysDept parentDept = getOne(wrapper);
            parentDept.setHasChildren("T");
            saveOrUpdate(parentDept);
            sysDept.setDeep(parentDept.getDeep() + 1);
        }
        save(sysDept);
        Long deptId = sysDept.getId();
        Long pid = dto.getPid();
        // 设置负责人
//        deptLeaderService.syncLeader(deptId, dto.getLeaders());
//        deptClosureService.create(deptId, pid);
        // 设置部门用户
        userDeptService.syncUser(deptId, dto.getLeaders());
        // 发布权限变更事件，刷新当前用户的权限信息
        LoginUser loginUser = LoginUtils.getLoginUser();
        if (loginUser != null) {
            // 1. 发布权限变更事件，会触发GlobalEventListener中的处理逻辑
            eventPublisher.publish(new PermissionChangeEvent(this, new PermissionMeta(Collections.singletonList(loginUser.getUserInfo().getId()))));
            // 2. 直接调用syncUserInfo方法，确保当前登录用户的部门信息被同步更新
            sysUserService.syncUserInfo(loginUser.getUserInfo().getId());
        }
    }

    @Transactional
    @Override
    public void update(SysDeptUpdateDTO dto) {
        SysDept sysDept = BeanCopyUtils.copy(dto, SysDept.class);
        QueryWrapper wrapper;
        // id有效性校验
        wrapper = QueryWrapper.create().eq(SysDept::getId, dto.getId());
        SysDept one = getOne(wrapper);
        Long oldPid = one.getPid();
        CommonResponseEnum.INVALID_ID.assertTrue(count(wrapper) <= 0);
        if (dto.getPid() == 0) {
            sysDept.setDeep(1);
        } else {
            wrapper = QueryWrapper.create().eq(SysDept::getId, dto.getPid());
            SysDept parent = getOne(wrapper);
            one.setHasChildren("T");
            saveOrUpdate(one);
            sysDept.setDeep(parent.getDeep() + 1);
        }
        // 设置负责人
        //deptLeaderService.syncLeader(dto.getId(), dto.getLeaders());
        // 设置部门用户
        userDeptService.syncUser(dto.getId(), dto.getLeaders());
        saveOrUpdate(sysDept);
        // 移动树
        if (!Objects.equals(oldPid, dto.getPid())) {
            deptClosureService.move(dto.getId(), dto.getPid());
        }
        
        // 刷新当前登录用户部门信息
        LoginUser loginUser = LoginUtils.getLoginUser();
        if (loginUser != null) {
            // 1. 发布权限变更事件，会触发GlobalEventListener中的处理逻辑
            eventPublisher.publish(new PermissionChangeEvent(this, new PermissionMeta(Collections.singletonList(loginUser.getUserInfo().getId()))));
            // 2. 直接调用syncUserInfo方法，确保当前登录用户的部门信息被同步更新
            sysUserService.syncUserInfo(loginUser.getUserInfo().getId());
        }
    }

    @Override
    public PageResult<SysDeptVO> page(SysDeptListDTO dto) {
        LoginUser loginUser = LoginUtils.getLoginUser();
        assert loginUser != null;
        
        // 获取用户直接关联的部门ID
        List<Long> directDeptIds = loginUser.getDepts();
        
        // 递归查询这些部门及其所有子部门（基于PID关系）
        Set<Long> deptAndChildren = new HashSet<>();
        if (directDeptIds != null && !directDeptIds.isEmpty()) {
            deptAndChildren.addAll(directDeptIds);
            findChildDepartments(directDeptIds, deptAndChildren);
        }

        // Check if deptAndChildren is empty to avoid SQL syntax error
        if (deptAndChildren == null || deptAndChildren.isEmpty()) {
            // Return empty page result if no departments to query
            return PageUtils.getPageResult(new Page<>());
        }

        QueryWrapper queryWrapper = buildQueryWrapper(dto).and(SYS_DEPT.ID.in(new ArrayList<>(deptAndChildren)));
        Page<SysDeptVO> page = pageAs(PageUtils.getPage(dto), queryWrapper, SysDeptVO.class);
        return PageUtils.getPageResult(page);
    }

    @Override
    public List<SysDeptVO> list(SysDeptListDTO dto) {
        LoginUser loginUser = LoginUtils.getLoginUser();
        assert loginUser != null;
        
        // 获取用户直接关联的部门ID
        List<Long> directDeptIds = loginUser.getDepts();
        
        // 递归查询这些部门及其所有子部门（基于PID关系）
        Set<Long> deptAndChildren = new HashSet<>();
        if (directDeptIds != null && !directDeptIds.isEmpty()) {
            deptAndChildren.addAll(directDeptIds);
            findChildDepartments(directDeptIds, deptAndChildren);
        }

        // Check if deptAndChildren is empty to avoid SQL syntax error
        if (deptAndChildren == null || deptAndChildren.isEmpty()) {
            return new ArrayList<>(); // Return empty list if no departments to query
        }

        QueryWrapper wrapper = QueryWrapper.create().select(SYS_DEPT.ALL_COLUMNS,
                QueryMethods.groupConcat(
                    if_(SYS_USER.DEL_FLAG.eq("F"), QueryMethods.concatWs(QueryMethods.string(":"),
                            SYS_USER_DEPT.USER_ID, SYS_USER.NICKNAME), null_())
                ).as("leader_info"),
                VEHICLE_SCHEDULE.TITLE.as("scheduleName")
        )
        .from(SYS_DEPT)
        //.leftJoin(SYS_DEPT_LEADER).on(SYS_DEPT.ID.eq(SYS_DEPT_LEADER.DEPT_ID))
        .leftJoin(SYS_USER_DEPT).on(SYS_DEPT.ID.eq(SYS_USER_DEPT.DEPT_ID))
        .leftJoin(SYS_USER).on(SYS_USER_DEPT.USER_ID.eq(SYS_USER.ID)).groupBy(SYS_DEPT.ID)
        .leftJoin(VEHICLE_SCHEDULE).as("vehicle_s").on(SYS_DEPT.SCHEDULE_ID.eq(VEHICLE_SCHEDULE.ID))
        .and(SYS_DEPT.ID.in(new ArrayList<>(deptAndChildren)));
        List<SysDeptVO> deptVOS = listAs(wrapper, SysDeptVO.class);
        SysDeptVO root = TreeUtils.getRoot(SysDeptVO.class);
        List<SysDeptVO> trees = TreeUtils.buildTree(deptVOS, root);
        return trees.getFirst().getChildren();
    }

    @Override
    public void remove(SelectIdsDTO dto) {
        List<Long> ids = (List<Long>) dto.getIds();
        CommonResponseEnum.INVALID_ID.assertTrue(ids.isEmpty());
        // 根据要删除的id，获取所有子集id
        List<Long> descendants = deptClosureService.descendants(ids);
        // 创建一个包含当前部门和所有子部门的ID列表
        List<Long> allIds = new ArrayList<>();
        allIds.addAll(ids);
        if (descendants != null && !descendants.isEmpty()) {
            allIds.addAll(descendants);
        }
        // 删除所有部门
        removeByIds(allIds);
    }

    @Override
    public SysDeptVO detail(Object id) {
        SysDept sysDept = getById((Serializable) id);
        CommonResponseEnum.INVALID_ID.assertNull(sysDept);
        SysDeptVO deptVO = BeanCopyUtils.copy(sysDept, SysDeptVO.class);
        // 查询指定部门的负责人
        //List<Long> leaderIds = QueryChain.of(leaderMapper).select(SYS_DEPT_LEADER.LEADER_ID).eq(SysDeptLeader::getDeptId, id).listAs(Long.class);
        List<Long> leaderIds = QueryChain.of(sysUserDeptMapper).select(SYS_USER_DEPT.USER_ID).eq(SysUserDept::getDeptId, id).listAs(Long.class);
        deptVO.setLeaders(leaderIds);
        return deptVO;
    }

    @Override
    public List<DeptTreeVO> getDepartmentTreeWithAdditionalNodes() {
        // 获取部门树
        List<DeptTreeVO> trees = getDeptTree(null, false, true);
        // 获取所有用户数量
        long allUserCount = count(QueryWrapper.create().from(SysUser.class));
        // 获取未设置部门的用户数量
        long unsetDeptCount = userMapper.countSysUserListNotDept();
        // 创建全部节点
        DeptTreeVO all = createAllNode(allUserCount);
        // 创建未设置部门节点
        DeptTreeVO unset = createUnsetNode(unsetDeptCount);
        // 将‘全部’、‘未设置部门’节点添加到集合头部
        trees.add(0, all);
        trees.add(1, unset);
        return trees;
    }

    private DeptTreeVO createUnsetNode(Long unsetDeptCount) {
        DeptTreeVO unset = new DeptTreeVO();
        unset.setId(-2L);
        unset.setName("未设置公司");
        AtomicReference<Long> total = new AtomicReference<>(0L);
        LogicDeleteManager.execWithoutLogicDelete(() -> total.set(unsetDeptCount));
        unset.setUserTotal(total.get());
        return unset;
    }

    private DeptTreeVO createAllNode(Long userCount) {
        DeptTreeVO all = new DeptTreeVO();
        all.setId(-1L);
        all.setName("全部");
        all.setUserTotal(userCount);
        return all;
    }

    @Override
    public List<DeptTreeVO> getDeptTree(Integer excludeNodeId, Boolean appendRoot, Boolean needSetTotal) {
        QueryWrapper wrapper = QueryWrapper.create()
                // .orderBy(SysDept::getDeep).asc()
                .orderBy(SysDept::getSort).asc();
        // 获取所有部门信息
        List<SysDept> list = list(wrapper);
        List<DeptTreeVO> deptTreeVOS = BeanCopyUtils.copyList(list, DeptTreeVO.class);
        if (needSetTotal != null && needSetTotal) {
            setUseTotal(deptTreeVOS);
        }
        DeptTreeVO root = TreeUtils.getRoot(DeptTreeVO.class);
        assert root != null;
        root.setName("总公司");
        List<DeptTreeVO> trees = TreeUtils.buildTree(deptTreeVOS, root, excludeNodeId);
        if (appendRoot != null && !appendRoot) {
            if (trees.getFirst().getChildren() == null) {
                trees = new ArrayList<>();
            } else {
                trees = trees.getFirst().getChildren();
            }
        }
        return trees;
    }

    /**
     * 一级树
     * @param
     */
    @Override
    public List<DeptTreeVO> getDeptTree1(Integer excludeNodeId, Boolean appendRoot, Boolean needSetTotal) {
        QueryWrapper wrapper = QueryWrapper.create()
                .where(SysDept::getPid).eq(0) // 只查询父ID为0的一级部门
                .orderBy(SysDept::getSort).asc();

        // 获取所有一级部门信息
        List<SysDept> list = list(wrapper);
        List<DeptTreeVO> deptTreeVOS = BeanCopyUtils.copyList(list, DeptTreeVO.class);

        if (needSetTotal != null && needSetTotal) {
            setUseTotal(deptTreeVOS);
        }

        // 如果您仍然需要构建树形结构（虽然只有一级）
        DeptTreeVO root = TreeUtils.getRoot(DeptTreeVO.class);
        assert root != null;
        root.setName("总公司");

        List<DeptTreeVO> trees = TreeUtils.buildTree(deptTreeVOS, root, excludeNodeId);

        if (appendRoot != null && !appendRoot) {
            if (trees.getFirst().getChildren() == null) {
                trees = new ArrayList<>();
            } else {
                trees = trees.getFirst().getChildren();
            }
        }
        return trees;
    }

    private void setUseTotal(List<DeptTreeVO> deptTreeVOS) {
        // 查询直属部门的数量
        QueryWrapper wrapper = QueryWrapper.create()
                .select(SYS_DEPT.ID, SYS_DEPT.NAME, QueryMethods.count(case_().when(SYS_USER.DEL_FLAG.eq("F")).then(SYS_USER_DEPT.USER_ID).end()).as("total"))
                .from(SYS_DEPT).leftJoin(SYS_USER_DEPT).on(SYS_DEPT.ID.eq(SYS_USER_DEPT.DEPT_ID)).leftJoin(SYS_USER).on(SYS_USER_DEPT.USER_ID.eq(SYS_USER.ID))
                .groupBy(SYS_DEPT.ID, SYS_DEPT.NAME).orderBy(SYS_DEPT.DEEP.asc()).orderBy(SYS_DEPT.SORT.asc());
        List<TotalDeptVO> totalDeptVOS = listAs(wrapper, TotalDeptVO.class);

        /*
         * 查询非直属部门的数量。
         *
         * SQL 查询语句： SELECT d.id, d.name, COUNT(ud.user_id) AS total FROM sys_dept d
         * LEFT JOIN sys_dept_closure c ON d.id = c.ancestor_id LEFT JOIN sys_user_dept
         * ud ON c.descendant_id = ud.dept_id GROUP BY d.id, d.name;
         *
         * 该查询通过 `LEFT JOIN` 连接 `sys_dept`、`sys_dept_closure` 和 `sys_user_dept` 三个表，
         * 统计每个部门下非直属的用户数量，并按部门 ID 和名称分组。
         */
        Map<Long, Long> totalDeptMap = new HashMap<>();
        if (totalDeptVOS != null) {
            totalDeptMap = totalDeptVOS.stream().collect(Collectors.toMap(TotalDeptVO::getId, TotalDeptVO::getTotal));
        }
        for (DeptTreeVO treeVO : deptTreeVOS) {
            if (totalDeptMap.containsKey(treeVO.getId())) {
                treeVO.setUserTotal(totalDeptMap.get(treeVO.getId()));
            }
        }
    }

    /**
     * 查询部门leader信息-穿梭框
     *
     * @return SysDeptLeaderVO
     */
    @Override
    public SysDeptLeaderVO findSysUserDeptLeader() {
        // 查询所有的用户
        List<SysDeptLeaderVO.LeaderInfoVO> userInfos = QueryChain.of(userMapper)
                .select(SYS_USER.ALL_COLUMNS)
                .from(SYS_USER)
                .leftJoin(SYS_USER_ROLE).on(SYS_USER.ID.eq(SYS_USER_ROLE.USER_ID))
                .where(SYS_USER.DEL_FLAG.eq("F"))
                .and(SYS_USER_ROLE.ROLE_ID.isNull().or(SYS_USER_ROLE.ROLE_ID.ne(7)))
                .groupBy(SYS_USER.ID)
                .listAs(SysDeptLeaderVO.LeaderInfoVO.class);
        SysDeptLeaderVO leaderVO = new SysDeptLeaderVO();
        leaderVO.setLeaderInfoVOS(userInfos);
        return leaderVO;
    }
    @Override
    public SysDeptLeaderVO findSysUserDeptLeader2() {
        // 查询所有的用户从user_dept表
        List<SysDeptLeaderVO.LeaderInfoVO> userInfos = QueryChain.of(sysUserDeptMapper)
                .select(SYS_USER.ID, SYS_USER.NICKNAME)
                .from(SYS_USER_DEPT)
                .leftJoin(SYS_USER).on(SYS_USER_DEPT.USER_ID.eq(SYS_USER.ID))
                .where(SYS_USER.DEL_FLAG.eq("F"))
                .groupBy(SYS_USER.ID, SYS_USER.NICKNAME)
                .listAs(SysDeptLeaderVO.LeaderInfoVO.class);
        SysDeptLeaderVO leaderVO = new SysDeptLeaderVO();
        leaderVO.setLeaderInfoVOS(userInfos);
        return leaderVO;
    }

    private static QueryWrapper buildQueryWrapper(SysDeptListDTO dto) {
        QueryWrapper queryWrapper = QueryWrapper.create().from(SysDept.class);
    
        if (dto.getName() != null && !dto.getName().isEmpty()) {
            queryWrapper.and(SysDept::getName).like(dto.getName());
        }
    
        if (dto.getSchedule_id() != null) {
            queryWrapper.and(SysDept::getSchedule_id).eq(dto.getSchedule_id());
        }
    
        return queryWrapper;
    }

    @Override
    public List<DeptTreeVO> getCurrentUserDeptTree(Boolean appendRoot, Boolean needSetTotal) {
        LoginUser loginUser = LoginUtils.getLoginUser();
        assert loginUser != null;
        List<Long> deptAndChildren = loginUser.getDeptAndChildren();
        
        // Check if deptAndChildren is empty to avoid SQL syntax error
        if (deptAndChildren == null || deptAndChildren.isEmpty()) {
            return new ArrayList<>(); // Return empty list if no departments to query
        }
        
        QueryWrapper wrapper = QueryWrapper.create()
                .where(SYS_DEPT.ID.in(deptAndChildren))
                .orderBy(SysDept::getSort).asc();
        
        // 获取用户有权限的部门信息
        List<SysDept> list = list(wrapper);
        List<DeptTreeVO> deptTreeVOS = BeanCopyUtils.copyList(list, DeptTreeVO.class);
        
        if (needSetTotal != null && needSetTotal) {
            setUseTotal(deptTreeVOS);
        }
        
        DeptTreeVO root = TreeUtils.getRoot(DeptTreeVO.class);
        assert root != null;
        root.setName("总公司");
        List<DeptTreeVO> trees = TreeUtils.buildTree(deptTreeVOS, root);
        
        if (appendRoot != null && !appendRoot) {
            if (trees != null && !trees.isEmpty() && trees.getFirst().getChildren() != null) {
                trees = trees.getFirst().getChildren();
            } else {
                trees = new ArrayList<>();
            }
        }
        
        return trees;
    }

    @Override
    public List<DeptTreeVO> getDeptTree2() {
        // 获取当前登录用户
        LoginUser loginUser = LoginUtils.getLoginUser();
        if (loginUser == null || loginUser.getDepts() == null || loginUser.getDepts().isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取用户直接关联的部门ID
        List<Long> directDeptIds = loginUser.getDepts();
        
        // 递归查询这些部门及其所有子部门（基于PID关系）
        Set<Long> allDeptIds = new HashSet<>(directDeptIds);
        findChildDepartments(directDeptIds, allDeptIds);
        
        // 查询用户部门及其子部门信息
        QueryWrapper wrapper = QueryWrapper.create()
                .where(SYS_DEPT.ID.in(allDeptIds))
                .orderBy(SysDept::getSort).asc();
        List<SysDept> list = list(wrapper);
        List<DeptTreeVO> deptTreeVOS = BeanCopyUtils.copyList(list, DeptTreeVO.class);
        
        DeptTreeVO root = TreeUtils.getRoot(DeptTreeVO.class);
        assert root != null;
        root.setName("总公司");
        List<DeptTreeVO> trees = TreeUtils.buildTree(deptTreeVOS, root);
        
        // 返回不带根节点的树形结构
        if (trees != null && !trees.isEmpty() && trees.getFirst().getChildren() != null) {
            return trees.getFirst().getChildren();
        }
        return new ArrayList<>();
    }

    /**
     * 递归查找子部门
     * 
     * @param parentDeptIds 父部门ID列表
     * @param result 结果集合
     */
    private void findChildDepartments(List<Long> parentDeptIds, Set<Long> result) {
        if (parentDeptIds.isEmpty()) {
            return;
        }
        
        // 查询父部门的直接子部门
        QueryWrapper childQuery = QueryWrapper.create()
            .select(SYS_DEPT.ID)
            .from(SYS_DEPT)
            .where(SYS_DEPT.PID.in(parentDeptIds))
            .and(SYS_DEPT.DEL_FLAG.eq("F"));
        
        List<SysDept> childDepts = list(childQuery);
        if (childDepts.isEmpty()) {
            return;
        }
        
        // 提取子部门ID
        List<Long> childDeptIds = childDepts.stream()
            .map(SysDept::getId)
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
        
        // 添加到结果中
        result.addAll(childDeptIds);
        
        // 递归查找子部门的子部门
        findChildDepartments(childDeptIds, result);
    }

    @Override
    public List<DepartmentVO> listSelector(SelectorQueryDTO dto) {
        QueryWrapper wrapper = QueryWrapper.create().select(SYS_DEPT.ID, SYS_DEPT.PID, SYS_DEPT.NAME, SYS_DEPT.SORT, SYS_DEPT.DEEP)
                .orderBy(SYS_DEPT.SORT.asc());
        // 获取所有部门信息
        List<DepartmentVO> list = listAs(wrapper, DepartmentVO.class);
        return TreeUtils.buildTree(list, 0);
    }

}